<template>
    <el-card>
        <div class="card-title">
            友链管理
        </div>
        <div class="search-container">
            <el-input v-model="searchModel.keyword"></el-input>
            <el-button icon="Refresh" @click="handleResetClick">重置</el-button>
            <el-button icon="Search" type="primary" @click="handleSearchClick">查询</el-button>
        </div>
        <div class="links-container">
            <div class="operation-btn">
                <el-button type="primary" icon="Plus" @click="handleAddClick">新增友链</el-button>
                <el-popconfirm width="200" title="是否确定删除当前勾选的友链数据?" @confirm="handleBatchDeleteClick">
                    <template #reference>
                        <el-button
                            type="danger"
                            icon="Delete"
                            :disabled="selectionGroup?.length! > 0 ? false : true"
                        >
                            批量删除
                        </el-button>
                    </template>
                </el-popconfirm>
            </div>
            <el-table
                :data="linkData"
                @selection-change="handleSelectChange">
                <el-table-column type="selection" align="center"></el-table-column>
                <el-table-column prop="linkAvatar" label="友链头像" align="center">
                    <template #default="scope">
                        <img class="link-avatar" :src="scope.row.linkAvatar" alt="">
                    </template>
                </el-table-column>
                <el-table-column prop="linkName" label="友链名称" align="center"></el-table-column>
                <el-table-column prop="linkAddress" label="友链地址" align="center"></el-table-column>
                <el-table-column prop="linkIntro" label="友链介绍" align="center"></el-table-column>
                <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
                <el-table-column label="操作"  align="center">
                    <template #default="scope">
                        <el-button type="primary" icon="EditPen" size="small" link @click="handleEditClick(scope.row)">编辑</el-button>
                        <el-popconfirm width="200" title="是否确定删除当前的友链数据?" @confirm="handleDeleteClick(scope.row.id)">
                            <template #reference>
                                <el-button type="danger" icon="Delete" size="small" link>删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                class="pagination-container"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="searchModel.current"
                :page-sizes="[5, 10, 20, 30]"
                :page-size="searchModel.size"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>
        <el-dialog
            :title="mode === 'add' ? '新增友链' : '修改友链'"
            v-model="linkVisible"
            width="450px"
            @close="handleCloseEvent(formRef!)">
            <el-form
                label-width="80px"
                ref="formRef"
                :model="formModel"
                :rules="rules">
                <el-form-item label="友链名称" prop="linkName">
                    <el-input v-model="formModel.linkName"></el-input>
                </el-form-item>
                <el-form-item label="头像地址" prop="linkAvatar">
                    <el-input v-model="formModel.linkAvatar"></el-input>
                </el-form-item>
                <el-form-item label="网址" prop="linkAddress">
                    <el-input v-model="formModel.linkAddress"></el-input>
                </el-form-item>
                <el-form-item label="介绍" prop="linkIntro">
                    <el-input v-model="formModel.linkIntro"></el-input>
                </el-form-item>
            </el-form>
            <div class="control-btns" style="margin-top: 70px;">
                <el-button size="large" @click="handleCancelClick(formRef!)">取消</el-button>
                <el-button type="primary" size="large" @click="handleConfirmCLick(formRef!)">确定</el-button>
            </div>
        </el-dialog>
    </el-card>
</template>

<script setup lang="ts">
import {
    createLinks,
    updateLinks,
    requestLinksDetail,
    requestLinksListPage,
    batchDeleteLinks
} from '@/service/common/link'
import { ref } from 'vue'
import type { ILinksItem } from './types'
import type { ILinksBody, ILinksParams } from '@/types/common'
import showMsg from '@/utils/message/message'
import { FormInstance, FormRules } from 'element-plus'

const mode = ref<string>('add')
const total = ref<number>(0)
const linkData = ref<ILinksItem[]>()
const selectionGroup = ref<ILinksItem[]>()
const linkVisible = ref<boolean>(false)
const formRef = ref<FormInstance>()
const searchModel = ref<ILinksParams>({
    current: 1,
    size: 5,
    keyword: ''
})
const formModel = ref<ILinksBody>({
    linkAddress: '',
    linkAvatar: '',
    linkIntro: '',
    linkName: ''
})
const rules = ref<FormRules>({
    linkAddress: [
        { required: true, message: '友链网址不能为空', trigger: 'blur' }
    ],
    linkAvatar: [
        { required: true, message: '头像地址不能为空', trigger: 'blur' }
    ],
    linkIntro: [
        { required: true, message: '友链介绍不能为空', trigger: 'blur' }
    ],
    linkName: [
        { required: true, message: '友链名称不能为空', trigger: 'blur' }
    ]
})

const handleSelectChange = (val: ILinksItem[]) => {
    selectionGroup.value = val
}

const handleResetClick = () => {
    searchModel.value = {
        current: 1,
        size: 5,
        keyword: ''
    }
    refreshPage()
}
const handleSearchClick = () => {
    refreshPage(true)
}

const handleAddClick = () => {
    formModel.value.id = ''
    mode.value = 'add'
    linkVisible.value = true
}

const handleEditClick = (row_data: ILinksItem) => {
  formModel.value.id = row_data.id!
  formModel.value.linkAddress = row_data.linkAddress!
  formModel.value.linkAvatar = row_data.linkAvatar!
  formModel.value.linkIntro = row_data.linkIntro!
  formModel.value.linkName = row_data.linkName!

  mode.value = 'modify'
  linkVisible.value = true
}

const handleDeleteClick = (id: number) => {
    batchDeleteLinks([id])
          .then((res) => {
              if (res.code === 2001) {
                  refreshPage()
                  showMsg('success', '删除成功')
              }
          })
}

const handleCloseEvent = (formEl: FormInstance) => {
    if (!formEl) return
    formEl.resetFields()

    formModel.value = {
        linkAddress: '',
        linkAvatar: '',
        linkIntro: '',
        linkName: ''
    }
}

const handleCancelClick = (formEl: FormInstance) => {
    if (!formEl) return
    formEl.resetFields()

    formModel.value = {
        linkAddress: '',
        linkAvatar: '',
        linkIntro: '',
        linkName: ''
    }

    linkVisible.value = false
}

const handleConfirmCLick = (formEl: FormInstance) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            if (mode.value === 'add') {
                requestCreateLink()
            } else if (mode.value === 'modify') {
                requestUpdateLink()
            }
        }
    })
}

const requestCreateLink = () => {
    createLinks(formModel.value)
        .then((res) => {
            if (res.code === 2001) {
                refreshPage()
                linkVisible.value = false
                showMsg('success', '新增成功')
            }
        })
}
const requestUpdateLink = () => {
    updateLinks(formModel.value)
        .then((res) => {
            if (res.code === 2001) {
                refreshPage()
                linkVisible.value = false
                showMsg('success', '修改成功')
            }
        })
}

/**
 * 批量删除
 */
 const handleBatchDeleteClick = () => {
    const ids: number[] = selectionGroup.value?.map((val) => {
        return val.id
    }) as number[]

    if (ids && ids.length > 0) {
      batchDeleteLinks(ids)
          .then((res) => {
              if (res.code === 2001) {
                  refreshPage()
                  showMsg('success', '删除成功')
              }
          })
    }
}

/**
 * 显示条数回调
 * @param size 条目数
 */
 const handleSizeChange = (size: number) => {
  searchModel.value.size = size
  refreshPage()
}
/**
 * 页码回调
 * @param current 当前页
 */
const handleCurrentChange = (current: number) => {
    searchModel.value.current = current
  refreshPage()
}

const refreshPage = (isShowMsg: boolean = false) => {
    requestLinksListPage(searchModel.value)
        .then((res) => {
            if (res.code === 2001) {
                if (isShowMsg) showMsg('success', '查询成功')
                linkData.value = res.data.records
                total.value = res.data.total
                searchModel.value.current = res.data.current
                searchModel.value.size = res.data.size
            }
        })
}

const init = () => {
    refreshPage()
}

init()
</script>

<style scoped lang="less">
.search-container {
    display: flex;
    :deep(.el-input) {
        width: 240px !important;
        margin-right: 10px;
    }
}
.links-container {
    .operation-btn {
        margin: 20px 0;
    }
}
.link-avatar {
    width: 80px;
    height: 80px;
    border-radius: 50%;
}
</style>
